import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ExFilter } from './exception/exception.filter';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { config } from '@/config/index';
import * as csurf from 'csurf';
import * as helmet from 'helmet';
import * as rateLimit from 'express-rate-limit';
import { NestExpressApplication } from '@nestjs/platform-express/interfaces/nest-express-application.interface';
import { Logger } from '@nestjs/common';
const { globalPrefix, port, loggerLevel, rate_limit, swagger, corsOptions } =
  config;
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: loggerLevel,
  });

  // xss
  app.use(helmet.xssFilter());
  app.use(helmet.hidePoweredBy());
  app.use(helmet.contentSecurityPolicy());

  // 如果在服务器和以太网之间存在负载均衡或者反向代理，Express可能需要配置为信任proxy设置的头文件，
  // 从而保证最终用户得到正确的IP地址。

  // app.set('trust proxy', 1);
  // 全局路由前缀
  app.setGlobalPrefix(globalPrefix);
  // 跨域

  app.enableCors(corsOptions);
  // xss crsf : json 验证 crsf没有用
  // app.use(csurf({ cookie: true }));

  // 限速
  app.use(rateLimit(rate_limit));

  // gzip
  // app.use(gzipMiddleware);

  // 全局错误处理中间件
  app.useGlobalFilters(new ExFilter());
  // console.log(swagger)
  if (swagger) {
    // 如果是生产环境，这里不需要
    const options = new DocumentBuilder()
      .setTitle('API文档')
      .setDescription('后端API')
      .setVersion('1.0.1')
      .addBearerAuth()
      .build();
    const document = SwaggerModule.createDocument(app, options);
    // 映射 sagger的路径 :
    SwaggerModule.setup('doc', app, document);
    Logger.warn(`swaggerURL : http://localhost:${port}/doc`);
  }

  await app.listen(port);
}

bootstrap();
